using System;
using System.Collections.Generic;
using System.Text;
using System.Workflow.Runtime;
using Microsoft.SharePoint.Workflow;
using System.Collections;
using System.Diagnostics;

namespace Custom.Workflow.Activities.InfoPath
{

    public enum FormSetValueType
    {
        InnerText = 1,
        InnerXml
    }
    [Serializable]
    public class FormSetFieldValueRequest
    {
        public IPAccessHelper IPAccessHelper;
        public FormSetValueType SetValueType;
        public string PropertyPath;
        public string PropertyValue;

    }
    [Serializable]
    internal class IPAccessService : IPendingWork
    {
        internal static readonly IPAccessService Instance = new IPAccessService();

        #region IPendingWork Members

        public void Commit(System.Transactions.Transaction transaction, ICollection items)
        {
            int saveErrCnt = 0;

            if (items.Count > 0)
            {
                IEnumerator myItems = items.GetEnumerator();

                myItems.MoveNext();

                IPAccessHelper ip = ((FormSetFieldValueRequest)myItems.Current).IPAccessHelper;

            reprocess:

                ip.LoadForm();

                this.ProcessFormSetFieldValueRequests(items, ip);

                try
                {
                    ip.SaveForm();
                }
                catch
                {
                    saveErrCnt++;

                    if (saveErrCnt > 3)
                        throw;
                    else
                        goto reprocess;

                }
            }

        }

        private void ProcessFormSetFieldValueRequests(ICollection req, IPAccessHelper ip)
        {
            foreach (FormSetFieldValueRequest r in req)
            {

                try
                {
                    if(r.SetValueType == FormSetValueType.InnerText)

                        ip.SetFormValueInnerText(r.PropertyPath,r.PropertyValue);

                    else
                        ip.SetFormValueInnerXml(r.PropertyPath, r.PropertyValue);
                }
                catch (Exception e)
                {
                    Exception we = Common.WrapWithFriedlyException(e, string.Format("Error updating in form at {0} where property path = {1} ", ip.FormFile.Url, r.PropertyPath));

                    EventLog.WriteEntry("Custom.Workflow.Activities.InfoPath.IPAccessService", we.ToString(), EventLogEntryType.Error);

                    throw we;

                }
            }
        }


        public void Complete(bool succeeded, System.Collections.ICollection items)
        {

        }

        public bool MustCommit(System.Collections.ICollection items)
        {
            return true;

        }

        #endregion
    }
}
